// https://www.lintcode.com/problem/longest-common-subsequence/

public class Solution {
    /**
     * @param A: A string
     * @param B: A string
     * @return: The length of longest common subsequence of A and B
     */
    public int longestCommonSubsequence(String A, String B) {
        // write your code here
        ret = 0;
        cache = new int[A.length()][B.length()];
        for (int i = 0; i < A.length(); ++i) {
            for (int j = 0; j < B.length(); ++j) {
                cache[i][j] = -1;
            }
        }
        _longestCommonSubsequence(A, B, 0, 0);
        return ret;
    }
    
    protected int _longestCommonSubsequence(String A, String B, int x, int y) {
        if ((x >= A.length()) || (y >= B.length())) {
            return 0;
        }
        if (cache[x][y] == -1) {
            if (A.charAt(x) != B.charAt(y)) {
                int lx = _longestCommonSubsequence(A, B, x + 1, y);
                int ly = _longestCommonSubsequence(A, B, x, y + 1);
                cache[x][y] = Math.max(lx, ly);
                
            } else {
                cache[x][y] = _longestCommonSubsequence(A, B, x + 1, y + 1) + 1; // +1是因为在xy位置匹配
            }
            ret = Math.max(ret, cache[x][y]);
            
        }
        return cache[x][y];
    }
    
    protected int ret;
    protected int[][] cache;
}